package com.k2data.k2app.service;

import com.k2data.k2app.domain.SysMenu;
import com.k2data.k2app.domain.SysRole;
import com.k2data.k2app.domain.vo.SimpleObject;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.SysRoleMapper;
import com.k2data.k2app.mapper.SysRoleMenuMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author lidong 17-3-6.
 */
@Log4j2
@Service
public class SysRoleService {

    @Autowired
    private SysRoleMapper sysRoleMapper;
    @Autowired
    public SysRoleMenuService sysRoleMenuService;
    @Autowired
    public SysRoleMenuMapper sysRoleMenuMapper;
    @Autowired
    public SysMenuService sysMenuService;

    @Transactional
    public long insert(SysRole sysRole) throws K2ResponseException {
        //1 添加角色
        sysRoleMapper.insertOfSelective(sysRole);
        //2 添加角色菜单关联关系
        int result = sysRoleMenuService.updateByRole(sysRole);
        return result;
    }

    @Transactional
    public int update(SysRole sysRole) throws K2ResponseException {
        sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        int result = sysRoleMenuService.updateByRole(sysRole);
        return result;
    }

    @Transactional
    public List<SysRole> getRolesByUser(Long userId){
        return sysRoleMapper.rolesByUserId(userId);
    }

    @Transactional
    public List<SimpleObject> getRolesSimple(){
        List<SysRole> roles = sysRoleMapper.queryList();
        List<SimpleObject> list = new ArrayList<>();
        if(roles != null){
            roles.stream().forEach(item -> {
                SimpleObject simpleObject = new SimpleObject();
                simpleObject.setLabel(item.getName());
                simpleObject.setValue(String.valueOf(item.getId()));
                list.add(simpleObject);
            });
        }
        return list;
    }
    public List<SysRole> queryList(){
        List<SysRole> roles = sysRoleMapper.queryList();
        for(SysRole sysRole:roles){
            List<String> menuIds = new ArrayList<>();
            List<SysMenu> list = sysMenuService.getMenusByRole(sysRole.getId(),false);
            for(SysMenu sysMenu:list){
                menuIds.add(String.valueOf(sysMenu.getId()));
            }
            sysRole.setMenuIds(menuIds);
        }
        return roles;
    }

    /**
     * 删除角色
     * @param id
     * @return
     * @throws Exception
     */
    @Transactional
    public int deleteById(Long id) throws Exception{
        //1 删除角色
        sysRoleMapper.deleteById(id);
        //2 删除角色和菜单的关联关系
        sysRoleMenuMapper.deleteByRoleId(id);
        return 1;
    }
}
